import { useSearchParams } from 'react-router-dom'
import Menus from '../../ui/Menus.jsx'
import Spinner from '../../ui/Spinner'
import Table from '../../ui/Table'
import CabinRow from './CabinRow'
import { useCabins } from './useCabins.js'
import Pagination from '../../ui/Pagination.jsx'

export default function CabinTable() {
	const { cabins, isLoading } = useCabins()
	const [searchParams] = useSearchParams()

	// 1. FILTER
	const discount = searchParams.get('discount') || 'all'
	let filteredCabins = cabins || []

	if (discount === 'with-discount')
		filteredCabins = cabins.filter((cabin) => cabin.discount)
	if (discount === 'no-discount')
		filteredCabins = cabins.filter((cabin) => !cabin.discount)

	// 2. SORT
	const sortBy = searchParams.get('sortBy') || 'startDate-asc'
	const [field, order] = sortBy.split('-')
	const modifier = order === 'asc' ? 1 : -1
	const sortedCabins = [...filteredCabins].sort(
		(a, b) => (a[field] - b[field]) * modifier,
	)

	if (isLoading) return <Spinner />

	return (
		<Menus>
			<Table columns='0.6fr 1.8fr 2.2fr 1fr 1fr 1fr'>
				<Table.Header>
					<div />
					<div>Cabin</div>
					<div>Capacity</div>
					<div>Price</div>
					<div>Discount</div>
					<div />
				</Table.Header>
				<Table.Body
					data={sortedCabins}
					render={(cabin) => (
						<CabinRow
							cabin={cabin}
							key={cabin.id}
						/>
					)}
				/>

				<Table.Footer>
					<Pagination count={sortedCabins.length} />
				</Table.Footer>
			</Table>
		</Menus>
	)
}
